<?php

namespace Tbf\Bundle\PackageBundle\RelationPackage;

use Tbf\Bundle\PackageBundle\ActionInterface;
use Tbf\Bundle\TbfBundle\Controller\TbfController;

/**
 * 创建一个关系
 * 这个地方有两种可能的删除方式,对于仅创建一个关系,顺序没有影响...
 * * 在第1个对象上获得第2个对象的列表,然后创建对应项 默认
 * * 在第2个对象上获得第1个对象的列表,然后创建对应项
 * doctrine有优化,这两种方式都不会取出所有的数据
 */
class BulkCreateManyManyAction extends TbfController implements ActionInterface
{
    /** @var  RelationControllerConfig */
    protected $config;
    public function setConfig(RelationControllerConfig $config)
    {
        $this->config = $config;
        if (!$this->config->hasGetAnotherListFunctionName('first')) {
            $this->config->reverseOrder();
        }
    }
    public function execute($input)
    {
        $err = $this->checkParameterExist($input,array(
            $this->config->getConditionName('first'),
            $this->config->getConditionName('second')));
        if ($err!==null) {
            return array(null,$err);
        }
        //查询出很多前台用户
        $qb = $this->getDM()->createQueryBuilder()
            ->from($this->config->getEntityClassName('first'),'first')
            ->select('first');
        $first_list = $this->get('tbf_database.list_query')->create()
            ->fromConditionalExpressArray($input[$this->config->getConditionName('first')])
            ->fromOrmQueryBuilder($qb)
            ->getResult();
        $qb = $this->getDM()->createQueryBuilder()
            ->from($this->config->getEntityClassName('second'),'second')
            ->select('second');
        $second_list = $this->get('tbf_database.list_query')->create()
            ->fromConditionalExpressArray($input[$this->config->getConditionName('second')])
            ->fromOrmQueryBuilder($qb)
            ->getResult();

        foreach ($first_list as $first) {
            $first_another_list_function_name = $this->config->getGetAnotherListFunctionName('first');
            $exist_second_list = $first->{$first_another_list_function_name}();
            foreach ($second_list as $second) {
                if (!$exist_second_list->contains($second)) {
                    $exist_second_list->add($second);
                }
            }
        }
        $this->getDM()->flush();

        return array(null,null);
    }
}
